<template>
  <div class="resignation-container">
    <!-- 标题与筛选区 -->
    <div class="header">
      <h2 class="title">离职申请管理</h2>
      <div class="filter-group">
        <el-select
            v-model="statusFilter"
            placeholder="申请状态"
            style="width: 160px; margin-right: 15px"
            @change="handleStatusChange"
        >
          <el-option label="全部申请" value="" />
          <el-option label="待处理" value="pending" />
          <el-option label="已同意" value="approved" />
          <el-option label="已拒绝" value="rejected" />
        </el-select>
        <el-input
            v-model="searchKey"
            placeholder="搜索姓名/部门"
            prefix-icon="Search"
            style="width: 240px"
            @keyup.enter="handleSearch"
        />
        <el-button
            type="primary"
            icon="Refresh"
            @click="refreshList"
        >
          刷新
        </el-button>
      </div>
    </div>

    <!-- 离职申请列表 -->
    <el-table
        :data="filteredApplications"
        border
        stripe
        style="width: 100%; margin-top: 20px"
        :header-cell-style="{
        background: '#f5f7fa',
        color: '#333',
        fontWeight: '500',
        height: '50px'
      }"
        :row-style="{ height: '60px' }"
    >
      <el-table-column
          prop="name"
          label="姓名"
          align="center"
          width="120"
      />
      <el-table-column
          prop="department"
          label="部门"
          align="center"
          width="160"
      />
      <el-table-column
          prop="position"
          label="职位"
          align="center"
          width="180"
      />
      <el-table-column
          prop="reason"
          label="离职原因"
          align="center"
      >
        <template #default="scope">
          <el-tooltip
              :content="scope.row.reason"
              placement="top"
              effect="light"
          >
            <div class="reason-text">{{ scope.row.reason }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
          prop="applyTime"
          label="申请时间"
          align="center"
          width="180"
      />
      <el-table-column
          prop="status"
          label="状态"
          align="center"
          width="120"
      >
        <template #default="scope">
          <el-tag
              :type="statusTypeMap[scope.row.status].type"
              effect="dark"
          >
            {{ statusTypeMap[scope.row.status].label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
          label="操作"
          align="center"
          width="220"
      >
        <template #default="scope">
          <template v-if="scope.row.status === 'pending'">
            <el-button
                type="success"
                icon="Check"
                @click="handleApprove(scope.row)"
                class="btn-approve"
            >
              同意
            </el-button>
            <el-button
                type="danger"
                icon="Close"
                @click="handleReject(scope.row)"
                class="btn-reject"
            >
              拒绝
            </el-button>
          </template>
          <template v-else>
            <el-button
                type="success"
                @click="handleViewDetail(scope.row)"
            >
              查看详情
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态 -->
    <div v-if="filteredApplications.length === 0" class="empty-state">
      <el-empty description="暂无离职申请记录" />
    </div>

    <!-- 拒绝理由弹窗 -->
    <el-dialog
        title="拒绝离职申请"
        v-model="rejectDialogVisible"
        width="400px"
        :lock-scroll='false'
    >
      <el-form :model="rejectForm" ref="rejectFormRef" :rules="rejectRules">
        <el-form-item
            label="拒绝理由"
            prop="reason"
            label-width="80px"
        >
          <el-input
              type="textarea"
              v-model="rejectForm.reason"
              placeholder="请填写拒绝理由"
              rows="4"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="confirmReject"
        >
          确认拒绝
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElLoading, ElEmpty } from 'element-plus';

// 状态映射表
const statusTypeMap = {
  pending: { label: '待处理', type: 'warning' },
  approved: { label: '已同意', type: 'success' },
  rejected: { label: '已拒绝', type: 'danger' }
};

// 筛选条件
const statusFilter = ref('');
const searchKey = ref('');

// 离职申请列表
const applications = ref([]);

// 拒绝弹窗相关
const rejectDialogVisible = ref(false);
const currentApplication = ref(null);
const rejectForm = reactive({ reason: '' });
const rejectFormRef = ref(null);
const rejectRules = {
  reason: [{ required: true, message: '请填写拒绝理由', trigger: 'blur' }]
};

// 筛选后的列表
const filteredApplications = computed(() => {
  return applications.value.filter(app => {
    // 状态筛选
    const statusMatch = !statusFilter.value || app.status === statusFilter.value;
    // 搜索筛选
    const searchMatch = !searchKey.value
        || app.name.includes(searchKey.value)
        || app.department.includes(searchKey.value);
    return statusMatch && searchMatch;
  });
});

// 页面初始化
onMounted(() => {
  fetchApplications();
});

// ------------------------- 后端接口预留位置 -------------------------
// 获取离职申请列表
const fetchApplications = async () => {
  const loading = ElLoading.service({ text: '加载申请列表中...' });
  try {
    // 实际接口调用
    // const res = await axios.get('/api/resignation/list', {
    //   params: { status: statusFilter.value }
    // });
    // applications.value = res.data.data;

    // 模拟数据
    applications.value = [
      {
        id: 1,
        name: '张三',
        department: '研发部',
        position: '前端工程师',
        reason: '个人职业发展规划',
        applyTime: '2025-08-01 09:30',
        status: 'pending'
      },
      {
        id: 2,
        name: '李四',
        department: '测试部',
        position: '测试工程师',
        reason: '家庭原因，需回老家发展',
        applyTime: '2025-07-28 14:20',
        status: 'pending'
      },
      {
        id: 3,
        name: '王五',
        department: '市场部',
        position: '市场专员',
        reason: '薪资待遇未达预期',
        applyTime: '2025-07-25 16:40',
        status: 'approved'
      }
    ];
  } catch (error) {
    ElMessage.error('加载失败，请重试');
    console.error('获取离职申请列表失败：', error);
  } finally {
    loading.close();
  }
};

// 同意离职申请
const approveApplication = async (id) => {
  try {
    // 实际接口调用
    // const res = await axios.post('/api/resignation/approve', { id });
    // return res.data;

    // 模拟接口成功
    return { code: 200, message: '操作成功' };
  } catch (error) {
    console.error('同意离职申请失败：', error);
    throw new Error('操作失败，请重试');
  }
};

// 拒绝离职申请
const rejectApplication = async (data) => {
  try {
    // 实际接口调用
    // const res = await axios.post('/api/resignation/reject', data);
    // return res.data;

    // 模拟接口成功
    return { code: 200, message: '操作成功' };
  } catch (error) {
    console.error('拒绝离职申请失败：', error);
    throw new Error('操作失败，请重试');
  }
};

// ------------------------- 交互逻辑 -------------------------
// 状态筛选变化
const handleStatusChange = () => {
  fetchApplications();
};

// 搜索
const handleSearch = () => {
  console.log('搜索关键词：', searchKey.value);
};

// 刷新列表
const refreshList = () => {
  fetchApplications();
  ElMessage.success('列表已刷新');
};

// 同意申请
const handleApprove = async (row) => {
  try {
    const res = await approveApplication(row.id);
    if (res.code === 200) {
      ElMessage.success('已同意离职申请');
      // 更新本地列表状态
      const index = applications.value.findIndex(item => item.id === row.id);
      if (index !== -1) {
        applications.value[index].status = 'approved';
      }
    }
  } catch (error) {
    ElMessage.error(error.message);
  }
};

// 打开拒绝弹窗
const handleReject = (row) => {
  currentApplication.value = row;
  rejectForm.reason = '';
  rejectDialogVisible.value = true;
};

// 确认拒绝
const confirmReject = async () => {
  await rejectFormRef.value.validate();

  try {
    const res = await rejectApplication({
      id: currentApplication.value.id,
      reason: rejectForm.reason
    });

    if (res.code === 200) {
      ElMessage.success('已拒绝离职申请');
      // 更新本地列表状态
      const index = applications.value.findIndex(
          item => item.id === currentApplication.value.id
      );
      if (index !== -1) {
        applications.value[index].status = 'rejected';
      }
      rejectDialogVisible.value = false;
    }
  } catch (error) {
    ElMessage.error(error.message);
  }
};

// 查看详情
const handleViewDetail = (row) => {
  ElMessage.info(`查看 ${row.name} 的离职申请详情`);
  // 可扩展：打开详情弹窗展示完整信息
};
</script>

<style scoped>
.resignation-container {
  padding: 24px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 16px rgba(0, 0, 0, 0.06);
  min-height: 600px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  margin: 0;
  color: #1f2329;
  font-size: 1.5rem;
  font-weight: 600;
}

.filter-group {
  display: flex;
  align-items: center;
}

.reason-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 300px;
}

.btn-approve {
  margin-right: 8px;
}

.empty-state {
  margin: 60px 0;
  text-align: center;
}

/* 表格悬停效果 */
.el-table__row:hover > td {
  background-color: #f7f8fa !important;
  transition: background-color 0.2s ease;
}

/* 按钮样式优化 */
:deep(.el-button--mini) {
  padding: 4px 10px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .filter-group {
    width: 100%;
    flex-wrap: wrap;
    gap: 10px;
  }
}
</style>